//
//  XYMainController.m
//  十年少
//
//  Created by 尧的mac on 15/11/28.
//  Copyright © 2015年 xxy.icom. All rights reserved.
//

#import "XYMainController.h"
#import "AFNetworking.h"
#import "MJExtension.h"
#import "XYMainModel.h"
#import "MBProgressHUD+MJ.h"
#import "XYMainViewCell.h"
#import "XYMainFrom.h"
#import "XYImageTableViewController.h"
#import "XYChatViewController.h"
#import "CollectViewController.h"
#import "XYMainViewCell.h"
#import "MBProgressHUD+MJ.h"
@interface XYMainController ()<UIActionSheetDelegate>
@property (nonatomic ,strong) NSMutableArray *array;
@property (nonatomic ,strong) XYMainViewCell *cellview;
@property(nonatomic,assign)NSInteger index;
@end

@implementation XYMainController
-(NSMutableArray *)array{
    if (_array == nil) {
        _array = [NSMutableArray array ];
    }
    return _array;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.index = 0;
    // 创建标题
    self.title = @"十年少";
    
    //导航栏
    [self setNavTitle];
    
    //导航栏下面
    [self promptData];
    
    //刷新数据
    [self getRefreshdata];
    
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //距顶部30个距离
    self.tableView.contentInset = UIEdgeInsetsMake(40, 0, 0, 0);


    self.view.userInteractionEnabled = YES;
    UISwipeGestureRecognizer * swipRight = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipAction:)];
    
     [self.view addGestureRecognizer:swipRight];
    

    self.tableView.showsVerticalScrollIndicator = NO;
}
-(void)swipAction:(UISwipeGestureRecognizer*)sender{

    if (sender.direction ==UISwipeGestureRecognizerDirectionRight) {
        XYImageTableViewController * imageContr = [[XYImageTableViewController alloc]init];
        [self.navigationController pushViewController:imageContr animated:YES];
    }


}
-(void)setNavTitle{
    self.navigationController.navigationBar.translucent = YES;
    
    
    // 创建右边的聊天按钮
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc]initWithTitle:@"来聊天" style:UIBarButtonItemStylePlain target:self action:@selector(rightAction:)];
    
    [self.navigationItem setRightBarButtonItem:rightButton];
    
    // 创建左边的收藏按钮
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]initWithTitle:@"收藏" style:UIBarButtonItemStylePlain target:self action:@selector(leftButton:)];
    [self.navigationItem setLeftBarButtonItem:leftButton];
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    
}
-(void)promptData{
    
    UIView * view = [[UIView alloc]init];
    CGFloat with = self.view.frame.size.width;
    CGFloat height = 40;
    CGFloat heightX = -40;
    view.frame = CGRectMake(0, heightX, with, height);
    [view setBackgroundColor:[UIColor whiteColor]];
   //左边
    UIButton * proButton = [[UIButton alloc]init];
    [proButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [proButton setTitle:@"文字" forState:UIControlStateNormal];
     proButton.frame = CGRectMake(0,0,with/2, 40);
     proButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    [view addSubview:proButton];
    
    //中间
    UIView *midView = [[UIView alloc]init];
    midView.backgroundColor = [UIColor grayColor];
    midView.frame =CGRectMake(CGRectGetMaxX(proButton.frame),0,1, 40);
    [view addSubview:midView];
    //右边
    UIButton * rightButton = [[UIButton alloc]init];
    [rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [rightButton setTitle:@"图片" forState:UIControlStateNormal];
    rightButton.frame = CGRectMake(CGRectGetMaxX(midView.frame),0,with/2, 40);
    rightButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    [view addSubview:rightButton];
    
    //底部
    UIView *bowView = [[UIView alloc]init];
    bowView.backgroundColor = [UIColor grayColor];
    bowView.frame =CGRectMake(0,CGRectGetMaxY(proButton.frame),with, 1);
    [view addSubview:bowView];
    //控制器Bar  将proButton 隐藏在Bar下面
    [self.view addSubview:view];

}

/** 刷新数据*/
-(void)getRefreshdata{
    UIRefreshControl * refresh = [[UIRefreshControl alloc]init];
    [refresh addTarget:self action:@selector(refreshAction:) forControlEvents:UIControlEventValueChanged];
    [refresh beginRefreshing];//自动刷新
    [self refreshAction:refresh];
    [self.view addSubview:refresh];
}

-(void)refreshAction:(UIRefreshControl *)sender{
    
    NSLog(@"aaaaaa");
    self.index++;
    NSString * index = [NSString stringWithFormat:@"%ld",self.index];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer  = [AFHTTPResponseSerializer serializer];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    //请求头
    [manager.requestSerializer setValue:@"e2c382ce8849e756b2847a79e2cfb8a0" forHTTPHeaderField:@"apikey"];
    
    if (self.array.count) {
        params[@"page"] = index;
    }else{
        params[@"page"] = @"1";
    }
    
    
    [manager GET:@"http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_text" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        NSMutableDictionary *showapi_res_bodyDict  = dict[@"showapi_res_body"];
        NSMutableArray *listArray = showapi_res_bodyDict[@"contentlist"];
        NSMutableArray *mutarray = [NSMutableArray array ];
        
        for (NSDictionary * dict in listArray) {
            //数据转模型
            XYMainModel * mainModel = [XYMainModel objectWithKeyValues:dict];
            XYMainFrom * mainFrom = [[XYMainFrom alloc]init];
            mainFrom.mainModel = mainModel;
            
            [mutarray addObject:mainFrom];
        }

        //mutabArray是新数据
        //self.array是旧数据
        
        NSMutableArray * tempArray = [NSMutableArray array];
        [tempArray addObjectsFromArray:mutarray];
        [tempArray addObjectsFromArray:self.array];
        
        self.array = tempArray;
        
        //刷新数据
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD showError:@"网络请求失败"];
    }];
    
    [sender endRefreshing];
}
/**
 *  聊天
 *
 *  @param sender
 */
- (void)rightAction:(UIBarButtonItem *)sender
{

    XYChatViewController *chat = [[XYChatViewController alloc]init];

    [self.navigationController pushViewController:chat animated:YES];

    
}
- (void)leftButton:(UIBarButtonItem *)sender
{
//     收藏
        CollectViewController *chat = [[CollectViewController alloc]init];
    
        [self.navigationController pushViewController:chat animated:YES];
    
    
}

#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
   XYMainViewCell * cell= [XYMainViewCell mainCell:tableView];
    //获取模型
    cell.mainFrom =self.array[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    self.cellview = cell;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
   XYMainFrom * mainModel =   self.array[indexPath.row];
    NSLog(@"%f",mainModel.cellHeight);
    return mainModel.cellHeight;

}


#pragma mark ---选中哪行单元格
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //获取选中行单元格
    self.cellview = [self.tableView cellForRowAtIndexPath:indexPath];
    UIActionSheet * sheet = [[UIActionSheet alloc]initWithTitle:@"选择操作" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"收藏" otherButtonTitles:nil, nil];
    [sheet showInView:self.view];
}

#pragma mark ---UIActionSheetDelegate协议方法
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex ==0) {//收藏
        CollectViewController * coll = [[CollectViewController alloc]init];
        self.detegate =coll;
        if ([self.detegate respondsToSelector:@selector(setCellData:andName:andPhone:)]) {
            
            [self.detegate setCellData:self andName:self.cellview.titleName.text andPhone:self.cellview.textName.text];
        }
        [MBProgressHUD showSuccess:@"添加成功"];
    }
    
}

@end
